package com.baidumap.administrator.happystudy.ui;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Toast;

import com.ab.http.OnMessageResponse;
import com.ab.util.AbMathUtil;
import com.ab.util.ListUtils;
import com.ab.util.ToastUtil;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidumap.administrator.happystudy.R;
import com.baidumap.administrator.happystudy.adapter.SupermarketAdapter;
import com.baidumap.administrator.happystudy.api.Api;
import com.baidumap.administrator.happystudy.base.AppBaseActivity;
import com.baidumap.administrator.happystudy.base.Constant;
import com.baidumap.administrator.happystudy.model.ShopList;
import com.baidumap.administrator.happystudy.module.main.MainActivity;
import com.baidumap.administrator.happystudy.utils.GlideUtil;
import com.baidumap.administrator.happystudy.view.SwipyRefreshLayout;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.socks.library.KLog;
import com.stx.xhb.xbanner.XBanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;


/**
 * 演示覆盖物的用法
 */
public class WaiMaiActivity extends AppBaseActivity implements SwipyRefreshLayout.OnRefreshListener, OnMessageResponse, XBanner.XBannerAdapter {

    /**
     * MapView 是地图主控件
     */
    @Bind(R.id.bmapView)
    MapView mMapView;
    private BaiduMap mBaiduMap;
    private Marker mMarkerA;
    private Marker mMarkerB;
    private Marker mMarkerC;
    private Marker mMarkerD;
    private InfoWindow mInfoWindow;

    // 初始化全局 bitmap 信息，不用时及时 recycle
    BitmapDescriptor bdA = BitmapDescriptorFactory
            .fromResource(R.mipmap.hongse);
    BitmapDescriptor bdB = BitmapDescriptorFactory
            .fromResource(R.mipmap.hongse);
    BitmapDescriptor bdC = BitmapDescriptorFactory
            .fromResource(R.mipmap.hongse);
    BitmapDescriptor bdD = BitmapDescriptorFactory
            .fromResource(R.mipmap.hongse);
    BitmapDescriptor bd = BitmapDescriptorFactory
            .fromResource(R.mipmap.hongse);
    BitmapDescriptor bdGround = BitmapDescriptorFactory
            .fromResource(R.mipmap.hongse);


    public ImageLoader loader;
    @Bind(R.id.list)
    ListView mListView;
    private ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private SupermarketAdapter mAdapter;
    private static int currentPage = 1;
    private ArrayList<Map<String, Object>> arrayList;


    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    @Bind(R.id.main_SwipyRefreshLayout)
    SwipyRefreshLayout mSwipyRefreshLayout;


    private Double mLatitude, mLongitude;//维度、精度
    private String mAddress;

    private String mCatrgoryId;
    ArrayList<HashMap<String, Object>> result = new ArrayList<>();
    private String mTitle;//标题

    @Bind(R.id.xbanner)
    XBanner mXBanner;

    private List<Integer> mImgesUrl;
    private List<String> mBannerDataList;

    @Override
    public void doBussinessBeforeOnCreate() {
        super.doBussinessBeforeOnCreate();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_wai_mai;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        getBundleValue();
        mBaiduMap = mMapView.getMap();
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(14.0f);
        mBaiduMap.setMapStatus(msu);

        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        initLocation();
        mLocationClient.start();

//        initOverlay();
        iniView();


    }

    @Override
    public void doBusiness(Context mContext) {
        super.doBusiness(mContext);
        setHeaderBack();
        setHeaderTitle(mTitle);
//        setHeaderTitle(R.string.chao_shi_di_tu);
        initXBanner();
    }

    private void getBundleValue() {
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {

            mCatrgoryId = bundle.getString("category_id");
            mTitle = bundle.getString("title");
        }
    }

    private void iniView() {
        // 设置分页第一页的索引 默认为0
        mSwipyRefreshLayout.setFirstIndex(currentPage);
        // 监听事件
        mSwipyRefreshLayout.setOnRefreshListener(this);
        // LoadImage初始化
        loader = ImageLoader.getInstance();
        currentPage = 1;
        mAdapter = new SupermarketAdapter(WaiMaiActivity.this, loader);

    }


    @Override
    public void onMessageResponse(String url, JSONObject jo) throws JSONException {

        if (url.equals(Constant.SHOP_LIST) && jo != null) {
            ShopList shopList = new ShopList(jo.toString());

            if (shopList != null) {


                if (shopList.getCode().equals("200")) {

                    List<ShopList.DataBean> dataBeanList = shopList.getData();


                    HashMap<String, Object> map = null;

                    for (int i = 0; i < dataBeanList.size(); i++) {

                        LatLng ll = new LatLng(Double.parseDouble(dataBeanList.get(i).getLat()), Double.parseDouble(dataBeanList.get(i).getLng()));
                        Bundle bundle = new Bundle();
                        bundle.putString("shop_id", dataBeanList.get(i).getShop_id());
                        bundle.putString("shop_name", dataBeanList.get(i).getShop_name());
                        MarkerOptions ooA = new MarkerOptions().position(ll).icon(bdA)
                                .zIndex(9).draggable(true).extraInfo(bundle);

                        mMarkerA = (Marker) (mBaiduMap.addOverlay(ooA));

                        ooA.animateType(MarkerOptions.MarkerAnimateType.drop);


                        map = new HashMap<>();
                        map.put("shop_id", dataBeanList.get(i).getShop_id());
                        map.put("shop_name", dataBeanList.get(i).getShop_name());
                        map.put("shop_img", Constant.DOMAIN + dataBeanList.get(i).getLogo());
                        map.put("shop_rating", dataBeanList.get(i).getShop_star());
                        map.put("shop_distance", AbMathUtil.round(dataBeanList.get(i).getDistance(), 2));
                        map.put("shop_walk_time", dataBeanList.get(i).getDelivery_time());
                        result.add(map);

                    }

                    list.addAll(result);//

                    ListUtils.removeDuplicate(list);

                    currentPageAdd(list);
                    mAdapter.bindData(list);

                    if (currentPage == 1) {

                        mListView.setAdapter(mAdapter);
                    }
                    mAdapter.notifyDataSetChanged();


                    // add ground overlay
                    LatLng southwest = new LatLng(mLatitude - 20, mLongitude - 20);
                    LatLng northeast = new LatLng(mLatitude + 20, mLongitude + 20);
                    LatLngBounds bounds = new LatLngBounds.Builder().include(northeast)
                            .include(southwest).build();

                    //OverlayOptions ooGround = new GroundOverlayOptions()
                    //.positionFromBounds(bounds).image(bdGround).transparency(0.8f);
                    //mBaiduMap.addOverlay(ooGround);

                    MapStatusUpdate u = MapStatusUpdateFactory
                            .newLatLng(bounds.getCenter());
                    mBaiduMap.setMapStatus(u);

                    mBaiduMap.setOnMarkerDragListener(new BaiduMap.OnMarkerDragListener() {
                        public void onMarkerDrag(Marker marker) {
                        }

                        public void onMarkerDragEnd(Marker marker) {
                            Toast.makeText(
                                    WaiMaiActivity.this,
                                    "拖拽结束，新位置：" + marker.getPosition().latitude + ", "
                                            + marker.getPosition().longitude,
                                    Toast.LENGTH_LONG).show();
                        }

                        public void onMarkerDragStart(Marker marker) {
                        }
                    });
                    mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker) {

                            String shop_id = marker.getExtraInfo().getString("shop_id");
                            String shop_name = marker.getExtraInfo().getString("shop_name");

                            Bundle bundle = new Bundle();
                            bundle.putString("shop_id", shop_id);
                            bundle.putString("title", shop_name);

                            startBundleActivity(bundle, MainActivity.class);

                            return false;
                        }
                    });


                } else {
                    ToastUtil.showMessage(this, shopList.getMsg());
                }
            }
            mSwipyRefreshLayout.setRefreshing(false);
        }
    }

    protected void currentPageAdd(ArrayList mListView) {
        KLog.e("========" + currentPage);
        if (mListView.size() % 20 == 0 && mListView.size() > 0) {
            currentPage++;
        }
    }

    @Override
    public void onMessageResponse(String url, JSONArray jo) throws JSONException {

    }

    @Override
    public void onMessageResponse(String url, String str) throws Exception {

    }


    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span = 1000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        mLocationClient.setLocOption(option);
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            //获取定位结果
            StringBuffer sb = new StringBuffer(256);

            sb.append("time : ");
            sb.append(location.getTime());    //获取定位时间

            sb.append("\nerror code : ");
            sb.append(location.getLocType());    //获取类型类型

            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());    //获取纬度信息

            mLatitude = location.getLatitude();
            mLongitude = location.getLongitude();

            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());    //获取经度信息

            sb.append("\nradius : ");
            sb.append(location.getRadius());    //获取定位精准度

            if (location.getLocType() == BDLocation.TypeGpsLocation) {

                // GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());    // 单位：公里每小时

                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());    //获取卫星数

                sb.append("\nheight : ");
                sb.append(location.getAltitude());    //获取海拔高度信息，单位米

                sb.append("\ndirection : ");
                sb.append(location.getDirection());    //获取方向信息，单位度

                sb.append("\naddr : ");
                sb.append(location.getAddrStr());    //获取地址信息


                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {

                // 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());    //获取地址信息
                mAddress = location.getAddrStr();
                sb.append("\noperationers : ");
                sb.append(location.getOperators());    //获取运营商信息

                sb.append("\ndescribe : ");
                sb.append("网络定位成功");


            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {

                // 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");

            } else if (location.getLocType() == BDLocation.TypeServerError) {

                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");

            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {

                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");

            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {

                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");

            }

            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());    //位置语义化信息

            List<Poi> list = location.getPoiList();    // POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }

            KLog.e("BaiduLocationApiDem", sb.toString());

            if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
//                ToastUtil.showMessage(WaiMaiActivity.this, "定位成功：" + mAddress + "," + location.getLocationDescribe());

                Api.shopList(WaiMaiActivity.this, 1, mCatrgoryId, mLatitude, mLongitude);
            }

        }
    }

    public void initOverlay() {
        // add marker overlay
        LatLng llA = new LatLng(36.138958, 120.435829);
        LatLng llB = new LatLng(36.138958, 120.435829);
        LatLng llC = new LatLng(36.138958, 120.435829);
        LatLng llD = new LatLng(36.138958, 120.435829);

        MarkerOptions ooA = new MarkerOptions().position(llA).icon(bdA)
                .zIndex(9).draggable(true);

        mMarkerA = (Marker) (mBaiduMap.addOverlay(ooA));
        MarkerOptions ooB = new MarkerOptions().position(llB).icon(bdB)
                .zIndex(5);

        ooB.animateType(MarkerOptions.MarkerAnimateType.drop);

        mMarkerB = (Marker) (mBaiduMap.addOverlay(ooB));
        MarkerOptions ooC = new MarkerOptions().position(llC).icon(bdC).zIndex(7);

        ooC.animateType(MarkerOptions.MarkerAnimateType.grow);

        mMarkerC = (Marker) (mBaiduMap.addOverlay(ooC));
        ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
        giflist.add(bdA);
        giflist.add(bdB);
        giflist.add(bdC);
        MarkerOptions ooD = new MarkerOptions().position(llD).icons(giflist)
                .zIndex(0);

        ooD.animateType(MarkerOptions.MarkerAnimateType.grow);

        mMarkerD = (Marker) (mBaiduMap.addOverlay(ooD));

        // add ground overlay
        LatLng southwest = new LatLng(36.138948, 120.435829);
        LatLng northeast = new LatLng(36.138960, 120.435850);
        LatLngBounds bounds = new LatLngBounds.Builder().include(northeast)
                .include(southwest).build();

        //OverlayOptions ooGround = new GroundOverlayOptions()
        //.positionFromBounds(bounds).image(bdGround).transparency(0.8f);
        //mBaiduMap.addOverlay(ooGround);

        MapStatusUpdate u = MapStatusUpdateFactory
                .newLatLng(bounds.getCenter());
        mBaiduMap.setMapStatus(u);

        mBaiduMap.setOnMarkerDragListener(new BaiduMap.OnMarkerDragListener() {
            public void onMarkerDrag(Marker marker) {
            }

            public void onMarkerDragEnd(Marker marker) {
                Toast.makeText(
                        WaiMaiActivity.this,
                        "拖拽结束，新位置：" + marker.getPosition().latitude + ", "
                                + marker.getPosition().longitude,
                        Toast.LENGTH_LONG).show();
            }

            public void onMarkerDragStart(Marker marker) {
            }
        });
    }

    /**
     * 清除所有Overlay
     *
     * @param view
     */
    public void clearOverlay(View view) {
        mBaiduMap.clear();
        mMarkerA = null;
        mMarkerB = null;
        mMarkerC = null;
        mMarkerD = null;
    }

    /**
     * 重新添加Overlay
     *
     * @param view
     */
    public void resetOverlay(View view) {
        clearOverlay(null);
        initOverlay();
    }

    private class SeekBarListener implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            // TODO Auto-generated method stub
            float alpha = ((float) seekBar.getProgress()) / 10;
            if (mMarkerA != null) {
                mMarkerA.setAlpha(alpha);
            }
            if (mMarkerB != null) {
                mMarkerB.setAlpha(alpha);
            }
            if (mMarkerC != null) {
                mMarkerC.setAlpha(alpha);
            }
            if (mMarkerD != null) {
                mMarkerD.setAlpha(alpha);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
        }

    }

    @Override
    protected void onPause() {
        // MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        // MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // MapView的生命周期与Activity同步，当activity销毁时需调用MapView.destroy()
        mMapView.onDestroy();
        super.onDestroy();
        // 回收 bitmap 资源
        bdA.recycle();
        bdB.recycle();
        bdC.recycle();
        bdD.recycle();
        bd.recycle();
        bdGround.recycle();
    }

    /**
     * 下拉刷新
     *
     * @param index 当前分页索引
     */
    @Override
    public void onRefresh(int index) {
        currentPage = 1;

        result.clear();
        list.clear();
        mAdapter.notifyDataSetChanged();
        Api.shopList(WaiMaiActivity.this, currentPage, mCatrgoryId, mLatitude, mLongitude);
    }

    /**
     * 加载更多
     *
     * @param index 当前分页索引
     */
    @Override
    public void onLoad(int index) {
//        mSwipyRefreshLayout.setRefreshing(false);
        Api.shopList(WaiMaiActivity.this, currentPage, mCatrgoryId, mLatitude, mLongitude);

    }

    /**
     * 初始化轮播图
     */

    private void initXBanner() {

        mImgesUrl = new ArrayList<>();

        int[] imgages = {R.mipmap.waimai_banner_001, R.mipmap.waimai_banner_002, R.mipmap.waimai_banner_003, R.mipmap.waimai_banner_004, R.mipmap.waimai_banner_005};

        for (int i = 0; i < imgages.length; i++) {
            mImgesUrl.add(imgages[i]);

        }

        //添加广告数据
        mXBanner.setData(mImgesUrl, null);//第二个参数为提示文字资源集合
        mXBanner.setmAdapter(this);
    }

    @Override
    public void loadBanner(XBanner banner, Object model, View view, int position) {

        GlideUtil.displayImg(this, mImgesUrl.get(position), view);
    }

}
